// 习题三
const fp = require('loadsh/fp')

class Container {
  static of(value) {
    return new Container(value)
  }

  constructor(value) {
    this._value = value
  }

  map(fn) {
    return Container.of(fn(this._value))
  }
}

class MayBe {
  static of(value) {
    return new MayBe(value)
  }

  constructor(value) {
    this._value = value
  }

  // 判断是否空值
  isNothing() {
    return this._value === null || this._value === undefined
  }

  // 重写map函数
  map(fn) {
    // 判断是否空值，是则返回一个值为null的容器，否则返回值为fn(this._value)的容器
    return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this._value))
  }
}

// 练习1
let maybe = MayBe.of([5, 6, 1])

let ex = (num, arr) => {
  return fp.map((v) => fp.add(v, num), arr)
}

let ex1 = fp.curry(ex)(1)
let maybe1 = maybe.map(ex1)
console.log(maybe1._value)


// 练习2
let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do'])
let ex2 = (value) => {
  return fp.first(value)
}
console.log(xs.map(ex2)._value)

// 练习3
let safeProp = fp.curry((x, o) => MayBe.of(o[x]))
let user = {
  id: 2,
  name: 'Albert'
}
let userName = safeProp('name', user)
let ex3 = (name) => {
  return fp.flowRight(fp.first, fp.curry(fp.split)(''))(name)
}

console.log(userName.map(ex3)._value)

//练习4
let ex4 = (n) => {
  return MayBe.of(n).map(parseInt)._value
}

console.log(ex4())
